/***********************************************************************
 *            Project: CoreCms
 *        ProjectName: 核心内容管理系统                                
 *                Web: https://www.corecms.net                      
 *             Author: 大灰灰                                          
 *              Email: jianweie@163.com                                
 *         CreateTime: 2025/2/7 18:22:50
 *        Description: 暂无
 ***********************************************************************/


using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using CoreCms.Net.Configuration;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.Entities.Expression;
using CoreCms.Net.Model.FromBody;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.Filter;
using CoreCms.Net.Loging;
using CoreCms.Net.IServices;
using CoreCms.Net.Utility.Helper;
using CoreCms.Net.Utility.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using SqlSugar;
using CoreCms.Net.Web.Admin.Infrastructure;

namespace CoreCms.Net.Web.Admin.Controllers
{
    /// <summary>
    /// 客户群体
    ///</summary>
    [Description("客户群体")]
    [Route("api/[controller]/[action]")]
    [ApiController]
    [RequiredErrorForAdmin]
    [Authorize(Permissions.Name)]
    public class CoreCmsCustomerGroupController : ControllerBase
    {
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly ICoreCmsCustomerGroupServices _CoreCmsCustomerGroupServices;

        /// <summary>
        /// 构造函数
        ///</summary>
        public CoreCmsCustomerGroupController(IWebHostEnvironment webHostEnvironment
            ,ICoreCmsCustomerGroupServices CoreCmsCustomerGroupServices
            )
        {
            _webHostEnvironment = webHostEnvironment;
            _CoreCmsCustomerGroupServices = CoreCmsCustomerGroupServices;
        }

        #region 获取列表============================================================
        // POST: Api/CoreCmsCustomerGroup/GetPageList
         /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("获取列表")]
        public async Task<AdminUiCallBack> GetPageList()
        {
            var jm = new AdminUiCallBack();
            var pageCurrent = Request.Form["page"].FirstOrDefault().ObjectToInt(1);
            var pageSize = Request.Form["limit"].FirstOrDefault().ObjectToInt(30);
            var where = PredicateBuilder.True<CoreCmsCustomerGroup>();
            //获取排序字段
            var orderField = Request.Form["orderField"].FirstOrDefault();

            Expression<Func<CoreCmsCustomerGroup, object>> orderEx = orderField switch
            {
                "id" => p => p.id,"groupName" => p => p.groupName,"isDefault" => p => p.isDefault,"isEnable" => p => p.isEnable,"createTime" => p => p.createTime,
                _ => p => p.id
            };

            //设置排序方式
            var orderDirection = Request.Form["orderDirection"].FirstOrDefault();
            var orderBy = orderDirection switch
            {
                "asc" => OrderByType.Asc,
                "desc" => OrderByType.Desc,
                _ => OrderByType.Desc
            };
            //查询筛选
			
			//id int
			var id = Request.Form["id"].FirstOrDefault().ObjectToInt(0);
            if (id > 0)
            {
                where = where.And(p => p.id == id);
            }
			//名字 varchar
			var groupName = Request.Form["groupName"].FirstOrDefault();
            if (!string.IsNullOrEmpty(groupName))
            {
                where = where.And(p => p.groupName.Contains(groupName));
            }
			//默认 bit
			var isDefault = Request.Form["isDefault"].FirstOrDefault();
            if (!string.IsNullOrEmpty(isDefault) && isDefault.ToLowerInvariant() == "true")
            {
                where = where.And(p => p.isDefault == true);
            }
            else if (!string.IsNullOrEmpty(isDefault) && isDefault.ToLowerInvariant() == "false")
            {
                where = where.And(p => p.isDefault == false);
            }
			//是否开启 bit
			var isEnable = Request.Form["isEnable"].FirstOrDefault();
            if (!string.IsNullOrEmpty(isEnable) && isEnable.ToLowerInvariant() == "true")
            {
                where = where.And(p => p.isEnable == true);
            }
            else if (!string.IsNullOrEmpty(isEnable) && isEnable.ToLowerInvariant() == "false")
            {
                where = where.And(p => p.isEnable == false);
            }
			// datetime
			var createTime = Request.Form["createTime"].FirstOrDefault();
            if (!string.IsNullOrEmpty(createTime))
            {
                if (createTime.Contains("到"))
                {
                    var dts = createTime.Split("到");
                    var dtStart = dts[0].Trim().ObjectToDate();
                    where = where.And(p => p.createTime > dtStart);
                    var dtEnd = dts[1].Trim().ObjectToDate();
                    where = where.And(p => p.createTime < dtEnd);
                }
                else
                {
                    var dt = createTime.ObjectToDate();
                    where = where.And(p => p.createTime > dt);
                }
            }
            //获取数据
            var list = await _CoreCmsCustomerGroupServices.QueryPageAsync(where, orderEx, orderBy, pageCurrent, pageSize, true);
            //返回数据
            jm.data = list;
            jm.code = 0;
            jm.count = list.TotalCount;
            jm.msg = "数据调用成功!";
            return jm;
        }
        #endregion

        #region 首页数据============================================================
        // POST: Api/CoreCmsCustomerGroup/GetIndex
        /// <summary>
        /// 首页数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("首页数据")]
        public AdminUiCallBack GetIndex()
        {
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };
            return jm;
        }
        #endregion

        #region 创建数据============================================================
        // POST: Api/CoreCmsCustomerGroup/GetCreate
        /// <summary>
        /// 创建数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("创建数据")]
        public AdminUiCallBack GetCreate()
        {
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };
            return jm;
        }
        #endregion

        #region 创建提交============================================================
        // POST: Api/CoreCmsCustomerGroup/DoCreate
        /// <summary>
        /// 创建提交
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("创建提交")]
        public async Task<AdminUiCallBack> DoCreate([FromBody]CoreCmsCustomerGroup entity)
        {
            var jm = new AdminUiCallBack();
            var model = _CoreCmsCustomerGroupServices.QueryByClause(p=>p.groupName==entity.groupName);
            if (model==null)
            {
                jm = await _CoreCmsCustomerGroupServices.InsertAsync(entity);
            }
            else
            {
                jm.msg = ""+entity.groupName+"已存在";
            }
            
            return jm;
        }
        #endregion

        #region 编辑数据============================================================
        // POST: Api/CoreCmsCustomerGroup/GetEdit
        /// <summary>
        /// 编辑数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("编辑数据")]
        public async Task<AdminUiCallBack> GetEdit([FromBody]FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _CoreCmsCustomerGroupServices.QueryByIdAsync(entity.id, false);
            if (model == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            jm.code = 0;
            jm.data = model;

            return jm;
        }
        #endregion

        #region 编辑提交============================================================
        // POST: Api/CoreCmsCustomerGroup/Edit
        /// <summary>
        /// 编辑提交
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("编辑提交")]
        public async Task<AdminUiCallBack> DoEdit([FromBody]CoreCmsCustomerGroup entity)
        {
            var jm = new AdminUiCallBack();
            var model = _CoreCmsCustomerGroupServices.QueryByClause(p => p.groupName == entity.groupName);
            if (model==null)
            {
                jm = await _CoreCmsCustomerGroupServices.UpdateAsync(entity);
            }
            else
            {
                jm.msg = "" + entity.groupName + "已存在";
            }
            return jm;
        }
        #endregion

        #region 删除数据============================================================
        // POST: Api/CoreCmsCustomerGroup/DoDelete/10
        /// <summary>
        /// 单选删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("单选删除")]
        public async Task<AdminUiCallBack> DoDelete([FromBody]FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _CoreCmsCustomerGroupServices.ExistsAsync(p => p.id == entity.id, true);
            if (!model)
            {
                jm.msg = GlobalConstVars.DataisNo;
				return jm;
            }
            jm = await _CoreCmsCustomerGroupServices.DeleteByIdAsync(entity.id);

            return jm;
        }
        #endregion

        #region 批量删除============================================================
        // POST: Api/CoreCmsCustomerGroup/DoBatchDelete/10,11,20
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("批量删除")]
        public async Task<AdminUiCallBack> DoBatchDelete([FromBody]FMArrayIntIds entity)
        {
            var jm = await _CoreCmsCustomerGroupServices.DeleteByIdsAsync(entity.id);
            return jm;
        }

        #endregion

        #region 预览数据============================================================
        // POST: Api/CoreCmsCustomerGroup/GetDetails/10
        /// <summary>
        /// 预览数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("预览数据")]
        public async Task<AdminUiCallBack> GetDetails([FromBody]FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _CoreCmsCustomerGroupServices.QueryByIdAsync(entity.id, false);
            if (model == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            jm.code = 0;
            jm.data = model;

            return jm;
        }
        #endregion

        #region 选择导出============================================================
        // POST: Api/CoreCmsCustomerGroup/SelectExportExcel/10
        /// <summary>
        /// 选择导出
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("选择导出")]
        public async Task<AdminUiCallBack> SelectExportExcel([FromBody]FMArrayIntIds entity)
        {
            var jm = new AdminUiCallBack();

            //创建Excel文件的对象
            var book = new HSSFWorkbook();
            //添加一个sheet
            var mySheet = book.CreateSheet("Sheet1");
            //获取list数据
            var listModel = await _CoreCmsCustomerGroupServices.QueryListByClauseAsync(p => entity.id.Contains(p.id), p => p.id, OrderByType.Asc, true);
            //给sheet1添加第一行的头部标题
            var headerRow = mySheet.CreateRow(0);
            var headerStyle = ExcelHelper.GetHeaderStyle(book);
            var cellNum = 0;

            var cell0 = headerRow.CreateCell(cellNum);
            cell0.SetCellValue("id");
            cell0.CellStyle = headerStyle;
            mySheet.SetColumnWidth(cellNum, 10 * 256);
            cellNum++;

            var cell1 = headerRow.CreateCell(cellNum);
            cell1.SetCellValue("名字");
            cell1.CellStyle = headerStyle;
            mySheet.SetColumnWidth(cellNum, 10 * 256);
            cellNum++;

            var cell2 = headerRow.CreateCell(cellNum);
            cell2.SetCellValue("默认");
            cell2.CellStyle = headerStyle;
            mySheet.SetColumnWidth(cellNum, 10 * 256);
            cellNum++;

            var cell3 = headerRow.CreateCell(cellNum);
            cell3.SetCellValue("是否开启");
            cell3.CellStyle = headerStyle;
            mySheet.SetColumnWidth(cellNum, 10 * 256);
            cellNum++;

            var cell4 = headerRow.CreateCell(cellNum);
            cell4.SetCellValue("");
            cell4.CellStyle = headerStyle;
            mySheet.SetColumnWidth(cellNum, 10 * 256);
            cellNum++;

            headerRow.Height = 30 * 20;
            var commonCellStyle = ExcelHelper.GetCommonStyle(book);

            //将数据逐步写入sheet1各个行
            for (var i = 0; i < listModel.Count; i++)
            {
                var rowTemp = mySheet.CreateRow(i + 1);
                var cellNumTemp = 0;

                    var rowTemp0 = rowTemp.CreateCell(cellNumTemp);
                        rowTemp0.SetCellValue(listModel[i].id.ToString());
                        rowTemp0.CellStyle = commonCellStyle;
                        cellNumTemp++;

                    var rowTemp1 = rowTemp.CreateCell(cellNumTemp);
                        rowTemp1.SetCellValue(listModel[i].groupName.ToString());
                        rowTemp1.CellStyle = commonCellStyle;
                        cellNumTemp++;

                    var rowTemp2 = rowTemp.CreateCell(cellNumTemp);
                        rowTemp2.SetCellValue(listModel[i].isDefault.ToString());
                        rowTemp2.CellStyle = commonCellStyle;
                        cellNumTemp++;

                    var rowTemp3 = rowTemp.CreateCell(cellNumTemp);
                        rowTemp3.SetCellValue(listModel[i].isEnable.ToString());
                        rowTemp3.CellStyle = commonCellStyle;
                        cellNumTemp++;

                    var rowTemp4 = rowTemp.CreateCell(cellNumTemp);
                        rowTemp4.SetCellValue(listModel[i].createTime.ToString());
                        rowTemp4.CellStyle = commonCellStyle;
                        cellNumTemp++;

            }
            // 导出excel
            string webRootPath = _webHostEnvironment.WebRootPath;
            string tpath = "/files/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "-CoreCmsCustomerGroup导出(选择结果).xls";
            string filePath = webRootPath + tpath;
            DirectoryInfo di = new DirectoryInfo(filePath);
            if (!di.Exists)
            {
                di.Create();
            }
            FileStream fileHssf = new FileStream(filePath + fileName, FileMode.Create);
            book.Write(fileHssf);
            fileHssf.Close();

            jm.code = 0;
            jm.msg = GlobalConstVars.ExcelExportSuccess;
            jm.data = tpath + fileName;

            return jm;
        }
        #endregion

        #region 查询导出============================================================
        // POST: Api/CoreCmsCustomerGroup/QueryExportExcel/10
        /// <summary>
        /// 查询导出
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("查询导出")]
        public async Task<AdminUiCallBack> QueryExportExcel()
        {
            var jm = new AdminUiCallBack();

            var where = PredicateBuilder.True<CoreCmsCustomerGroup>();
                //查询筛选
			
			//id int
			var id = Request.Form["id"].FirstOrDefault().ObjectToInt(0);
            if (id > 0)
            {
                where = where.And(p => p.id == id);
            }
			//名字 varchar
			var groupName = Request.Form["groupName"].FirstOrDefault();
            if (!string.IsNullOrEmpty(groupName))
            {
                where = where.And(p => p.groupName.Contains(groupName));
            }
			//默认 bit
			var isDefault = Request.Form["isDefault"].FirstOrDefault();
            if (!string.IsNullOrEmpty(isDefault) && isDefault.ToLowerInvariant() == "true")
            {
                where = where.And(p => p.isDefault == true);
            }
            else if (!string.IsNullOrEmpty(isDefault) && isDefault.ToLowerInvariant() == "false")
            {
                where = where.And(p => p.isDefault == false);
            }
			//是否开启 bit
			var isEnable = Request.Form["isEnable"].FirstOrDefault();
            if (!string.IsNullOrEmpty(isEnable) && isEnable.ToLowerInvariant() == "true")
            {
                where = where.And(p => p.isEnable == true);
            }
            else if (!string.IsNullOrEmpty(isEnable) && isEnable.ToLowerInvariant() == "false")
            {
                where = where.And(p => p.isEnable == false);
            }
			// datetime
			var createTime = Request.Form["createTime"].FirstOrDefault();
            if (!string.IsNullOrEmpty(createTime))
            {
                if (createTime.Contains("到"))
                {
                    var dts = createTime.Split("到");
                    var dtStart = dts[0].Trim().ObjectToDate();
                    where = where.And(p => p.createTime > dtStart);
                    var dtEnd = dts[1].Trim().ObjectToDate();
                    where = where.And(p => p.createTime < dtEnd);
                }
                else
                {
                    var dt = createTime.ObjectToDate();
                    where = where.And(p => p.createTime > dt);
                }
            }
            //获取数据
            //创建Excel文件的对象
            var book = new HSSFWorkbook();
            //添加一个sheet
            var mySheet = book.CreateSheet("Sheet1");
            //获取list数据
            var listModel = await _CoreCmsCustomerGroupServices.QueryListByClauseAsync(where, p => p.id, OrderByType.Asc, true);
            //给sheet1添加第一行的头部标题
                var headerRow = mySheet.CreateRow(0);
            var headerStyle = ExcelHelper.GetHeaderStyle(book);
            var cellNum = 0;
            
            var cell0 = headerRow.CreateCell(cellNum);
            cell0.SetCellValue("id");
            cell0.CellStyle = headerStyle;
            mySheet.SetColumnWidth(cellNum, 10 * 256);
            cellNum++;
			
            var cell1 = headerRow.CreateCell(cellNum);
            cell1.SetCellValue("名字");
            cell1.CellStyle = headerStyle;
            mySheet.SetColumnWidth(cellNum, 10 * 256);
            cellNum++;
			
            var cell2 = headerRow.CreateCell(cellNum);
            cell2.SetCellValue("默认");
            cell2.CellStyle = headerStyle;
            mySheet.SetColumnWidth(cellNum, 10 * 256);
            cellNum++;
			
            var cell3 = headerRow.CreateCell(cellNum);
            cell3.SetCellValue("是否开启");
            cell3.CellStyle = headerStyle;
            mySheet.SetColumnWidth(cellNum, 10 * 256);
            cellNum++;
			
            var cell4 = headerRow.CreateCell(cellNum);
            cell4.SetCellValue("");
            cell4.CellStyle = headerStyle;
            mySheet.SetColumnWidth(cellNum, 10 * 256);
            cellNum++;
			

            headerRow.Height = 30 * 20;
            var commonCellStyle = ExcelHelper.GetCommonStyle(book);

            //将数据逐步写入sheet1各个行
            for (var i = 0; i < listModel.Count; i++)
            {
                var rowTemp = mySheet.CreateRow(i + 1);
                var cellNumTemp = 0;

            var rowTemp0 = rowTemp.CreateCell(cellNumTemp);
                rowTemp0.SetCellValue(listModel[i].id.ToString());
                rowTemp0.CellStyle = commonCellStyle;
                cellNumTemp++;

            var rowTemp1 = rowTemp.CreateCell(cellNumTemp);
                rowTemp1.SetCellValue(listModel[i].groupName.ToString());
                rowTemp1.CellStyle = commonCellStyle;
                cellNumTemp++;

            var rowTemp2 = rowTemp.CreateCell(cellNumTemp);
                rowTemp2.SetCellValue(listModel[i].isDefault.ToString());
                rowTemp2.CellStyle = commonCellStyle;
                cellNumTemp++;

            var rowTemp3 = rowTemp.CreateCell(cellNumTemp);
                rowTemp3.SetCellValue(listModel[i].isEnable.ToString());
                rowTemp3.CellStyle = commonCellStyle;
                cellNumTemp++;

            var rowTemp4 = rowTemp.CreateCell(cellNumTemp);
                rowTemp4.SetCellValue(listModel[i].createTime.ToString());
                rowTemp4.CellStyle = commonCellStyle;
                cellNumTemp++;

            }
            // 写入到excel
            string webRootPath = _webHostEnvironment.WebRootPath;
            string tpath = "/files/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "-CoreCmsCustomerGroup导出(查询结果).xls";
            string filePath = webRootPath + tpath;
            DirectoryInfo di = new DirectoryInfo(filePath);
            if (!di.Exists)
            {
                di.Create();
            }
            FileStream fileHssf = new FileStream(filePath + fileName, FileMode.Create);
            book.Write(fileHssf);
            fileHssf.Close();

            jm.code = 0;
            jm.msg = GlobalConstVars.ExcelExportSuccess;
            jm.data = tpath + fileName;

            return jm;
        }
        #endregion

        
        #region 设置默认============================================================
        // POST: Api/CoreCmsCustomerGroup/DoSetisDefault/10
        /// <summary>
        /// 设置默认
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("设置默认")]
        public async Task<AdminUiCallBack> DoSetisDefault([FromBody]FMUpdateBoolDataByIntId entity)
        {
            var jm = new AdminUiCallBack();

            var oldModel = await _CoreCmsCustomerGroupServices.QueryByIdAsync(entity.id, false);
            if (oldModel == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            oldModel.isDefault = (bool)entity.data;

            var bl = await _CoreCmsCustomerGroupServices.UpdateAsync(p => new CoreCmsCustomerGroup() { isDefault = oldModel.isDefault }, p => p.id == oldModel.id);
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.EditSuccess : GlobalConstVars.EditFailure;

            return jm;
		}
        #endregion
        
        #region 设置是否开启============================================================
        // POST: Api/CoreCmsCustomerGroup/DoSetisEnable/10
        /// <summary>
        /// 设置是否开启
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("设置是否开启")]
        public async Task<AdminUiCallBack> DoSetisEnable([FromBody]FMUpdateBoolDataByIntId entity)
        {
            var jm = new AdminUiCallBack();

            var oldModel = await _CoreCmsCustomerGroupServices.QueryByIdAsync(entity.id, false);
            if (oldModel == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            oldModel.isEnable = (bool)entity.data;

            var bl = await _CoreCmsCustomerGroupServices.UpdateAsync(p => new CoreCmsCustomerGroup() { isEnable = oldModel.isEnable }, p => p.id == oldModel.id);
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.EditSuccess : GlobalConstVars.EditFailure;

            return jm;
		}
        #endregion
        

    }
}
